<?php
namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Models\Wechat\Wechater;
use Illuminate\Http\Request;

use DB;
use Illuminate\Support\Fluent;

class SecretController extends Controller
{
    public function __construct()
    {

    }

    public function index()
    {
        echo 'index';
    }

    public function loadWechaters(Request $request)
    {
        ini_set('max_execution_time',3600);
        ini_set('set_time_limit',3600);

        $lastWechater = Wechater::orderBy('id','desc')->first();
        $nextOpenId = $lastWechater? $lastWechater->openid : null;

        $requestUrl = "http://kitty.wunsun.net/apps/mp/secret?nextId={$nextOpenId}";

        $responseData = file_get_contents($requestUrl);

        $responseData = new Fluent(json_decode($responseData));

        if(isset($responseData['status']) && $responseData['status'] == 200) {
            #success
            $result = DB::transaction(function () use ($responseData) {
                foreach ($responseData->lists as $obj)
                {

                    $model = new Wechater();
                    $model->fill((array)$obj);
                    $model->save();
                }

                return true;
            });

            return $result ?
                'success' :
                'fail';
        }
        else
        {
            #fail
            echo 'fail';
        } 
    }
}